package com.haibara.codesubmiteval.chain.userChain;

import cn.hutool.core.util.StrUtil;
import com.haibara.codesubmiteval.model.dto.user.UserAddRequest;
import com.haibara.codesubmiteval.model.entity.User;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import static com.haibara.codesubmiteval.constant.UserConstant.SALT;


/**
 * 处理密码默认值的节点
 *
 * @Author: mengyu
 * @Date: 2025/4/28
 */
@Component
@Order(4)
public class PasswordDefaultValueHandler extends CreateUserDefaultValueHandler {
    @Override
    public void handleDefaultValue(User user, UserAddRequest userAddRequest) {
        String password = userAddRequest.getPassword();
        Long id = userAddRequest.getId();
        // 如果密码未设定，则默认为学号
        if (StrUtil.isBlankIfStr(password)) {
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + id).getBytes());
            user.setPassword(encryptPassword);
        } else {
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
            user.setPassword(encryptPassword);
        }
        if (next != null) next.handleDefaultValue(user, userAddRequest);
    }
}
